<?php
/**
 * Author: ThanhTV
 * Email: thanhtran@vietnambiz.com
 * Date: Web,28/04/2011
 */
class company_model extends MY_Model{

    var $table = 'company';

    function company_model()
    {
    	parent::MY_Model();
        $this->set_table($this->table);
    }

    function get_company_info($id=0)
    {
    	$query = $this->db->where('id', $id)->get($this->table);
        if($query->num_rows() > 0) {
            $data = $query->row();
        }
        return $data;
    }

    function get_max_order()
    {
        return $this->db->select_max('order', 'max_order')->get($this->table)->row()->max_order;
    }

    function del_company($id)
    {
        return $this->db->where('id', $id)->delete($this->table);
    }

    function get_all_company($page=1 ,$limit= 20)
    {
        $this->db->select()
                 ->from($this->table)                
                 ->limit($limit, ($page - 1)*$limit)
                 ->order_by('order ASC');
        $q = $this->db->get();
        $result = $q->result();
        $q->free_result();
        return $result;
    }

    function get_count_all_company($active="")
    {
		$this->db->select("count(id) as m")->from($this->table);
		if(!empty($active))
		{
	    	$this->db->where("status",$active);
		}
        $rs = $this->db->get()->row();
        return $rs->m;
    }

    function check_name($name = '')
    {
        $q  =   $this->db->select()->from($this->table)->where('name',$name)->get();
        if($q->row())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    function check_name_edit($name = '',$id=0)
    {
        $where = array(
            'name'      => $name,
            'id !='     => $id
        );
        $q  =   $this->db->select()->from($this->table)->where($where)->get();
        if($q->row())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    function change_order($id, $old_order, $new_order)
    {          	
        $max_order = $this->get_max_order();

        if ($new_order < 1 || $new_order > $max_order)
            return false;

        $query = $this->db->get_where('company', array('order' => $new_order));

        if ($query->num_rows() > 0) 
        {
            $data = $query->row_array();            
            $this->db->update('company', array('order' => $old_order), array('id' => $data['id']));
            $this->db->update('company', array('order' => $new_order), array('id' => $id));
        }
        else 
        {
            $this->db->update('company', array('order' => $new_order), array('id' => $id));
        }
    }
}